package com.mzy.referencetest.cmdassociation;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName
 * @Description
 * @Author dyf
 * @Date 2020/3/27
 * @Version 1.0
 */
@Slf4j
public class CmdUtils {

    private CmdUtils() {
        throw new IllegalStateException("Utility class");
    }

    @Getter
    @Setter
    public static class Msg {
        private boolean state;
        private int code;
        private String inputText;
        private String errorText;

        @Override
        public String toString() {
            return "Msg{" +
                    "state=" + state +
                    ", inputText='" + inputText + '\'' +
                    ", code='" + code + '\'' +
                    ", errorText='" + errorText + '\'' +
                    '}';
        }
    }

    public static Msg execCmd(int timeout, String charsetName, String... commands) throws IOException, InterruptedException {
        Msg msg = new Msg();

        if (commands == null) {
            msg.setState(false);
            return msg;
        }
        if (timeout <= 0)
            timeout = 1;
        if (charsetName == null)
            charsetName = "UTF-8";

        System.out.println(commands);

//        Process process = Runtime.getRuntime().exec(commands);
//        boolean state = process.waitFor(timeout, TimeUnit.SECONDS);
//        // JDK9 API
//        byte[] isb = process.getInputStream().readAllBytes();
//        byte[] esb = process.getErrorStream().readAllBytes();
//        String ist = isb != null && isb.length > 0 ? new String(isb, charsetName) : null;
//        String est = esb != null && esb.length > 0 ? new String(esb, charsetName) : null;
//
//        msg.setState(state);
//        msg.setCode(process.exitValue());
//        msg.setErrorText(est);
//        msg.setInputText(ist);

        return msg;
    }

    public static Msg execCmd(int timeout, String charsetName, String commands) throws IOException, InterruptedException {
        Msg msg = new Msg();

        if (commands == null) {
            msg.setState(false);
            return msg;
        }
        if (timeout <= 0)
            timeout = 1;
        if (charsetName == null)
            charsetName = "UTF-8";


        Process process = Runtime.getRuntime().exec(commands);
        boolean state = process.waitFor(timeout, TimeUnit.SECONDS);
        // JDK9 API
//        byte[] isb = process.getInputStream().readAllBytes();
//        byte[] esb = process.getErrorStream().readAllBytes();
//        String ist = isb != null && isb.length > 0 ? new String(isb, charsetName) : null;
//        String est = esb != null && esb.length > 0 ? new String(esb, charsetName) : null;
//
//        msg.setState(state);
//        msg.setCode(process.exitValue());
//        msg.setErrorText(est);
//        msg.setInputText(ist);

        return msg;
    }

}